package de.hijacksoft.isle.adapters;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import de.hijacksoft.isle.classes.Item;
import de.hijacksoft.isle.classes.Price;
import de.hijacksoft.isle.R;
import de.hijacksoft.isle.classes.Variables;

/**
 * The Adapter for the ListView used in the ItemSelectActivity and RecipeActivity
 * @author HiJackSoft
 */
public class MainListAdapter extends BaseAdapter {

    // Constants
    private static final String TAG = "MainListAdapter";
    // option numbers for the modes
    public static final int CHECKBOX = 1;
    public static final int PRICE = 2;
    public static final int ICONS = 3;
    public static final int CATEGORIES = 4;
    public static final int AMOUNT = 5;
    public static final int BARCODE = 6;
    public static final int LASTBOUGHT = 7;
    // textViewResourceId used to inflate the layout
    private int id;
    private ArrayList<Item> items;
    private Context context;
    private DBAdapter adapter;
    // settings
    private boolean setting_checkbox, setting_price, setting_icons, setting_categories, setting_amount, setting_lastbought = true;
    private boolean setting_barcode = false;

    public MainListAdapter(Context context, int textViewResourceId, ArrayList<Item> objects, DBAdapter adapter) {
        this.id = textViewResourceId;
        this.items = objects;
        this.adapter = adapter;
        this.context = context;
    }

    /**
     * Sets the display mode of the list
     * @param mode the mode to be used
     * @param value enable (true) or disable (false) mode
     */
    public void setMode(int mode, boolean value) {
        switch (mode) {
            case CHECKBOX:
                setting_checkbox = value;
                break;
            case PRICE:
                setting_price = value;
                break;
            case ICONS:
                setting_icons = value;
                break;
            case CATEGORIES:
                setting_categories = value;
                break;
            case AMOUNT:
                setting_amount = value;
                break;
            case LASTBOUGHT:
                setting_lastbought = value;
                break;
            case BARCODE:
                setting_barcode = value;
                break;
        }
    }

    private boolean allChecked() {
        for (int i = 0; i < items.size(); i++) {
            if (!items.get(i).bought) {
                return false;
            }
        }
        return true;
    }

    public void onAllChecked() {
        // This method wants to be implemented <3
    }

    public void onDataSetChange() {
        // This method wants to be implemented <3
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        onDataSetChange();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {

        if (convertView == null) {
            LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(id, null);
        }

        // get the Views
        ImageView barcode = (ImageView) convertView.findViewById(R.id.item_barcode_icon);
        ImageView photo = (ImageView) convertView.findViewById(R.id.item_photo);
        final CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.item_checkbox);
        TextView name = (TextView) convertView.findViewById(R.id.item_name);
        TextView amount = (TextView) convertView.findViewById(R.id.item_amount);
        TextView price = (TextView) convertView.findViewById(R.id.item_price);
        TextView lastbought = (TextView) convertView.findViewById(R.id.item_date);
        ImageView category = (ImageView) convertView.findViewById(R.id.item_category);

        // set the category color
        if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Variables.PREFERENCE_SHOWCATEGORY, false)) {
            category.setVisibility(View.GONE);
        } else {
            if (items != null && items.get(position).category != null) {
                category.setBackgroundColor(items.get(position).category.color);
            }
        }


        // enable/disable barcode icon
        if (!this.setting_barcode) {
            barcode.setVisibility(View.GONE);
        } else {
            if (items.get(position).barcode == 0) {
                barcode.setVisibility(View.GONE);
            } else {
                barcode.setVisibility(View.VISIBLE);
            }
        }

        // enable/disable price text
        if (!this.setting_price) {
            price.setVisibility(View.GONE);
        } else {
            price.setVisibility(View.VISIBLE);
        }

        price.setText(new Price(context, items.get(position).price).toString());
        name.setText(items.get(position).name);

        // enable/disable lastbought text
        if (!this.setting_lastbought) {
            lastbought.setVisibility(View.GONE);
        } else {
            lastbought.setText(context.getString(R.string.lastbought).replace("$n", "" + ((System.currentTimeMillis() - items.get(position).lastbought) / 86400000)));
        }

        // enable/disable checkbox and check if all items are checked on each click
        if (!this.setting_checkbox) {
            checkbox.setVisibility(View.GONE);
        } else {
            checkbox.setVisibility(View.VISIBLE);

            checkbox.setChecked(items.get(position).bought);
            Log.v(TAG, "bought " + items.get(position).name + ": " + items.get(position).bought);

            checkbox.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    items.get(position).bought = checkbox.isChecked();
                    adapter.onItemBought(items.get(position));
                    if (allChecked()) {
                        onAllChecked();
                    }
                }
            });

        }

        // enable/disable item icon (depending on preferences and settings)
        if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Variables.PREFERENCE_SHOWICONS, true) || !setting_icons) {
            photo.setVisibility(View.GONE);
        } else {

            photo.setVisibility(View.VISIBLE);

            try {
                Log.d(TAG, items.get(position).name + ": " + items.get(position).image.toString());
                photo.setImageBitmap(readBitmap(items.get(position).image));
            } catch (Exception e) {
                Log.d(TAG, "Error reading bitmap: " + e.toString());
                photo.setImageDrawable(context.getResources().getDrawable(R.drawable.noicon));
            }

        }

        String unit = "?";
        switch (items.get(position).unit) {
            case 'k':
                unit = context.getString(R.string.unit_kg);
                break;
            case 'l':
                unit = context.getString(R.string.unit_l);
                break;
            case 'm':
                unit = context.getString(R.string.unit_ml);
                break;
            case 'g':
                unit = context.getString(R.string.unit_g);
                break;
            case 'p':
                unit = context.getString(R.string.unit_pc);
                break;
        }

        if (!this.setting_amount) {
            amount.setVisibility(View.GONE);
        } else {
            amount.setVisibility(View.VISIBLE);
        }

        amount.setText((Math.rint(items.get(position).amount * 100) / 100) + " " + unit);

        return convertView;

    }

    /**
     * @author Lumis (StackOverflow)
     * @param selectedImage An Uri to an image
     * @return returns the image as a Bitmap object
     */
    private Bitmap readBitmap(Uri selectedImage) {
        Bitmap bm = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2; //reduce quality 
        AssetFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
        } catch (FileNotFoundException e) {
            // e.printStackTrace(); // modified by HiJack Soft for Android
            Log.d(TAG, "Error reading a bitmap: " + e.getMessage());
        } finally {
            try {
                bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
                fileDescriptor.close();
            } catch (IOException e) {
                // e.printStackTrace(); // modified by HiJack Soft for Android
                Log.d(TAG, "Error reading a bitmap: " + e.getMessage());
            }
        }
        return bm;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int arg0) {
        return items.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }
}
